package com.elite.groovy.callback

import com.elite.groovy.util.EliteBean
import cn.com.elite.PropertiesUtil
import cn.com.kh.HttpClientProxy
import com.elite.groovy.kh.KHDBConfig
import net.sf.json.JSONObject
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import cn.com.tp.CompanyApiSign;
import cn.com.tp.AESCBCEncryption;
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 * 获取字节跳动短链接
 *
 */
public class apiGetDyUrl implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(apiGetDyUrl.class);

    @Override
    String doCallBack(EliteBean eliteBean, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
        httpServletResponse.setCharacterEncoding("UTF-8");
        //初始化返回参数
        JSONObject result = new JSONObject();

        //获取接口调用方式及参数
        String GetMethod = httpServletRequest.getMethod();
        log.debug("[GetMethod]:" + GetMethod);

        String inData = "";
        if (GetMethod.equals("GET")) {
            inData = httpServletRequest.getParameter("data");
            log.debug("[原始Get请求参数：]" + inData);
        } else {
            InputStreamReader reader = new InputStreamReader(httpServletRequest.getInputStream(), "UTF-8");
            BufferedReader iny = new BufferedReader(reader);
            String line;
            while ((line = iny.readLine()) != null) {
                inData += line;
            }
            log.debug("[原始Post请求参数：]" + inData);
        }


        try {

            JSONObject json = new JSONObject();
            json.put("pageType", "promotionPage");

            //获取配置里请加解密key
            String aesKey = KHDBConfig.getParam(eliteBean, "DY-KEY","");//获取字节跳动秘钥   "fP1bD1xB3fO0cY2bY3dW4aQ6cM6oY5eC";
            //请求内容加密
            String content = AESCBCEncryption.encrypt(json.toString(), aesKey, "", "UTF-8");
            log.debug("content:" + content);

            String requestID = System.currentTimeMillis() + new Random().nextInt(99999).toString();
            CompanyApiSign companyApiSign = new CompanyApiSign("taiping", requestID, content, System.currentTimeMillis() / 1000 as long);
            //获取签字
            String sign = companyApiSign.calcSign(companyApiSign, aesKey);
            log.debug("sign:" + sign);
            JSONObject json2 = new JSONObject();

            json2.put("companyID", "taiping");
            json2.put("timestamp", System.currentTimeMillis() / 1000 as int);
            json2.put("requestID", requestID);
            json2.put("sign", sign);
            json2.put("content", content);

            log.debug("json2.toString():" + json2.toString());
            List GetUrl = eliteBean.chaxun_sql(" select WEBSERVICEURL from sysc_interface where webtype='DY_ZJTD' ", "dataSource");
            String URL = GetUrl.get(0).get("WEBSERVICEURL");
            PropertiesUtil cfg = new PropertiesUtil();
            String proxyIp = cfg.readValue("QingNiu.ProxyIP");
            String proxyPort = cfg.readValue("QingNiu.ProxyPort");

            //通过代理访问
            String backjsonbody = HttpClientProxy.sendPost(URL, json2.toString(), proxyIp, proxyPort as int);

            //解密
            JSONObject inJson = JSONObject.fromObject(backjsonbody);
            String agencyCode = inJson.getString("content");//返回的报文
            String backcode = inJson.getString("code");//返回的code标识
            String backmsg = inJson.getString("msg");//返回的msg通告
            //判断抖音接口是否调用正常tb0000
            if (!backcode.equals("tb0000")) {
                result.put("code", backcode);
                result.put("msg", backmsg);
                result.put("link", "获取抖音短链异常");
            } else {
                //开始解密
                String link = AESCBCEncryption.decrypt(agencyCode, aesKey, "", "UTF-8");
                result.put("code", backcode);
                result.put("msg", backmsg);
                result.put("link", link);

            }
        } catch (Exception e) {
            log.error("获取抖音短链异常：", e);
            result.put("code", -1);
            result.put("msg", e.getMessage());
            result.put("link", "获取抖音短链异常")
        }


        return result;
    }

    static void main(String[] args) {
        JSONObject json = new JSONObject();
        json.put("pageType", "promotionPage");

        //获取配置里请加解密key
        String aesKey = "fP1bD1xB3fO0cY2bY3dW4aQ6cM6oY5eC";//获取字节跳动秘钥
        //请求内容加密
        String content = AESCBCEncryption.encrypt(json.toString(), aesKey, "", "UTF-8");
        log.debug("content:" + content);

        String requestID = System.currentTimeMillis() + new Random().nextInt(99999).toString();
        String agencyCode = "QIyQ+je7i86J2RZVZn2RYiBTGKXVZtbxW+GvmS0B2vxjPhWu4LLeOkpeTW5HfCO1oAFptkwO/gOFlQUo+HBAB4F8hgkcq9Jn+WYx2gxFQM1DvFRzW3rAiR7WiXwM66if4nHOZHg3UdXXmwQ03QMbNMK6lg0S2JIVmDGkStabg+gTJrGwPxECQIaOcFnLxjPmXvA2BrMAA1OX98ArYhG1c/n9HCvCfznYmL3MZN1EdULelt5FP3K126BN++FvYVZOBLqyolVFYzmWQXjtrE1e+BcO15Va5F47xcwpUBy4QCVdTwrzTEy5zIryHLhQe4fK";

        //返回的报文
        CompanyApiSign companyApiSign = new CompanyApiSign("taiping", requestID, content, System.currentTimeMillis() / 1000 as long);
        System.out.println("link" + companyApiSign)
        //获取签字
        String sign = companyApiSign.calcSign(companyApiSign, aesKey);
        System.out.println("sign" + sign)
        //解密
        String link = AESCBCEncryption.decrypt(agencyCode, "fP1bD1xB3fO0cY2bY3dW4aQ6cM6oY5eC", "", "UTF-8");

        System.out.println("link" + link)
    }
}
